package com.bifrost.task;

import com.bifrost.cbentity.StoreAccount;
import com.bifrost.cbrepository.StoreAccountRepository;
import com.bifrost.constant.CustomerSyncFlag;
import com.bifrost.entity.Customer;
import com.bifrost.repository.CustomerRepository;
import com.bifrost.util.DateUtils;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 每天凌晨1点同步门店会员数据到中间库
 *
 * @author rangf
 * @date 2018/12/17
 */
@Component
@JobHandler("customerSyncTask")
public class CustomerSyncTask extends IJobHandler {

    private static Logger LOGGER = LoggerFactory.getLogger(CustomerSyncTask.class);

    @Autowired
    CustomerRepository customerRepository;
    @Autowired
    StoreAccountRepository storeAccountRepository;

    @PersistenceContext(unitName = "mainEntityManagerFactory")
    protected EntityManager em;

    @Transactional(value = "transactionManagerPrimary")
    @Override
    public ReturnT<String> execute(String s) {
        try {
            XxlJobLogger.log("同步门店会员信息开始...");
            List<Customer> customerList = customerRepository.findBySyncFalseAndLoyaltyCardNotNullAndMerchantStoreNotNull();
            if (CollectionUtils.isNotEmpty(customerList)) {
                String now = DateUtils.format(new Date(), "yyyyMMdd");
                List<StoreAccount> storeAccountList = new ArrayList<>(customerList.size());
                List<Customer> customers = new ArrayList<>(customerList.size());
                for (Customer customer : customerList) {
                    customer.setSync(Boolean.TRUE);
                    customers.add(customer);
                    StoreAccount e = new StoreAccount();
                    e.setStoreCode(customer.getMerchantStore().getStoreCode());
                    e.setLoyaltyCard(customer.getLoyaltyCard());
                    e.setOpenID(customer.getUnionId());
                    if(null != customer.getUpdatedTimestamp())
                        e.setUpdateDate(DateUtils.format(customer.getUpdatedTimestamp(), "yyyyMMddHHmmss"));
                    e.setCreatedOn(now);
                    e.setFlag(CustomerSyncFlag.CREATE);
                    e.setStatus("0");
                    storeAccountList.add(e);
                    e = null;
                }
                storeAccountRepository.save(storeAccountList);
                for (int i = 0; i < customers.size(); i++) {
                    em.merge(customers.get(i));
                    if (i % 1000 == 0) {
                        em.flush();
                        em.clear();
                    }
                }
            }
        } catch (Exception e) {
            XxlJobLogger.log("同步门店会员信息失败:" + e.getMessage(), e);
        }
        return ReturnT.SUCCESS;
    }

}
